package com.pan.crawler.old;


import com.pan.download3.ctrl.BlockCtrl;
import com.pan.download3.ctrl.TaskCtrl;
import com.pan.download3.ctrl.WriteCtrl;
import com.pan.entity.Chapter;
import com.pan.entity.ThreadTask;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Driver {

    private BlockCtrl blockCtrl;

    private TaskCtrl taskCtrl;

    private WriteCtrl writeCtrl;


    public Driver(){
    }

    public void init(String directoryUrl){
        Directory directory = new Directory();
        directory.run(directoryUrl);
        String bookName = directory.getBookName();
        List<Chapter> chapterList = directory.getChapterList();
        blockCtrl = new BlockCtrl();
        taskCtrl = new TaskCtrl(chapterList);
        writeCtrl = new WriteCtrl(bookName,blockCtrl);
    }
    public void run(String directoryUrl){
        this.run(directoryUrl,10,10);
    }

    public void run(String directoryUrl,int corePoolSize, int maximumPoolSize){
        init(directoryUrl);
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,10, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10),
                new ThreadPoolExecutor.CallerRunsPolicy());
        for (int i = 0; i < maximumPoolSize; i++) {
            poolExecutor.execute(()->{
                Page page = new Page();
                boolean flag = true;
                while (flag){
                    Chapter chapter = this.taskCtrl.getTask();
                    System.out.println(Thread.currentThread().getName()+"开始下载："+chapter.toString());
                    if (chapter == null){
                        break;
                    }
                    else {
                        String content = null;
                        try {
                             content = page.get(chapter);
                        }catch (Exception e){
                            taskCtrl.cancelTask(chapter);
                            continue;
                        }
                        while (true) {
                            if (!writeCtrl.append(content, chapter.getId())) {
                                blockCtrl.block(new ThreadTask(chapter, Thread.currentThread()));
                            }
                            else break;
                        }
                        System.out.println(Thread.currentThread().getName()+"下载成功："+chapter.toString());
                    }
                }
            });
        }
        poolExecutor.shutdown();

    }
}
